<template>
  <div>
    <van-nav-bar title="搜索中心" left-arrow @click-left="$router.back()" />
    <van-search
      v-model.trim="value"
      shape="round"
      show-action
      placeholder="请输入搜索关键词"
      @input="doSuggest"
      @search="onSearch"
    >
      <template #action>
        <div @click="onSearch">搜索</div>
      </template>
    </van-search>

    <!-- 历史记录 -->
    <van-cell-group v-if="value == ''">
      <van-cell title="历史记录" />
      <van-cell
        @click="onHistory(item)"
        v-for="(item, index) in historyList"
        :key="index"
        :title="item"
      />
    </van-cell-group>

    <!-- 搜索建议 -->
    <van-cell-group v-else>
      <van-cell v-for="(item, index) in colorList" :key="index" icon="search">
        <template #title>
          <div v-html="item" @click="onHistory(suggestList[index])"></div>
        </template>
      </van-cell>
    </van-cell-group>
  </div>
</template>

<script>
import { suggestAPI, searchAPI } from '@/api/search'
export default {
  name: 'Search',
  data () {
    return {
      value: '',
      suggestList: [],
      historyList: JSON.parse(localStorage.getItem('history95')) || []
    }
  },
  computed: {
    colorList () {
      // 依赖了请求得到的数组，而且长度要保持一致
      return this.suggestList.map(v => {
        // 把每一项中的关键字找出来，并把它们包成`span`，加一个行内样式
        return v.replaceAll(
          this.value,
          `<span style="color:red;">${this.value}</span>`
        )
      })
    }
  },
  methods: {
    // 点击历史记录做跳转
    onHistory (item) {
      this.value = item
      this.onSearch()
    },
    // 当输入框内容有改变就调用
    async doSuggest () {
      // 非空判断
      if (this.value === '') return
      // 发请求获取搜索建议
      const res = await suggestAPI({
        q: this.value
      })
      // 保存起来
      // console.log(res)
      if (res.data.options[0] === null) {
        this.suggestList = []
      } else {
        this.suggestList = res.data.options
      }
    },
    // 点击搜索
    async onSearch () {
      // 非空判断
      if (this.value === '') return this.$toast('请输入内容')

      // 跳转之前先把搜索保存成历史记录
      // 先判断内容在不在原来的数组里
      const idx = this.historyList.indexOf(this.value)
      if (idx !== -1) {
        this.historyList.splice(idx, 1)
      }
      // 把搜索的内容存到数组里
      this.historyList.unshift(this.value)
      localStorage.setItem('history95', JSON.stringify(this.historyList))

      // const res = await searchAPI({
      //   q: this.value
      // })
      // console.log(res)
      this.$router.push({ name: 'results', query: { value: this.value } })
    }
  }
}
</script>

<style></style>
